﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace CLUBsInterpreter.ObjectTypes
{
	/**
	 * <summary>
	 * Describes a cell object in the CLUBs environment.
	 * </summary>
	 **/
	class CLUBsCell : CLUBsObject, Visual.IPaintable
	{

		new public Scope LocalVariables
		{
			get
			{
				if (base.LocalVariables.ContainsKey("MaxPieces"))
				{
					if (!base.LocalVariables.ContainsKey("Full"))
					{
						base.LocalVariables.Declare("Full", (CLUBsBoolean)false);
					}
					if ((CLUBsInteger)base.LocalVariables["MaxPieces"] <= Pieces.Count &&
						(CLUBsInteger)base.LocalVariables["MaxPieces"] != -1)
					{
						base.LocalVariables["Full"].CopyValueFromObject((CLUBsBoolean)true);
					}
					else if ((CLUBsInteger)base.LocalVariables["MaxPieces"] > Pieces.Count ||
							 (CLUBsInteger)base.LocalVariables["MaxPieces"] == -1)
					{
						base.LocalVariables["Full"].CopyValueFromObject((CLUBsBoolean)false);
					}
				}
				return base.LocalVariables;
			}
		}

		public List<CLUBsPiece> Pieces = new List<CLUBsPiece>();

		public bool Selectable = false;

		/**
		 * <summary>
		 * Default constructor creates cell object, setting default properties.
		 * </summary>
		 **/
		public CLUBsCell()
		{
			// Set the object identifier type
			ObjectIdentifierType = AST.IdentifierType.Cell;
			// SPECIFY STANDARD ENVIRONMENT
			// Max pieces in the cell, default -1 (no limit)
			base.LocalVariables.Declare("MaxPieces", new CLUBsInteger(-1));
			base.LocalVariables.Declare("Full", (CLUBsBoolean)false);
			base.LocalVariables.Declare("X", new CLUBsInteger());
			base.LocalVariables.Declare("Y", new CLUBsInteger());
		}

		/**
		 * <see cref="CLUBsObject.CopyValueFromObject"/>
		 **/
		public override void CopyValueFromObject(CLUBsObject obj)
		{
			CLUBsCell cellObj = (CLUBsCell)obj;
			LocalVariables.Clear();
			foreach (KeyValuePair<string, CLUBsObject> var in obj.LocalVariables)
			{
				LocalVariables.Declare(var.Key, CLUBsObject.GenerateSimpleObject(var.Value.ObjectIdentifierType));
				LocalVariables[var.Key].CopyValueFromObject(var.Value);
			}
		}

		public void Paint(object sender, System.Windows.Forms.PaintEventArgs args)
		{
			Graphics g = args.Graphics;
			Rectangle clip = args.ClipRectangle;
			Rectangle cellRect = new Rectangle(clip.X, clip.Y, clip.Width - 1, clip.Height - 1);
			Pen p = new Pen(Color.Black, 1.0f);
			p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
			g.DrawRectangle(p, cellRect);
			if (StandardEnvironment.Instance.SelectingCell && this.Selectable)
			{
				g.FillRectangle(new SolidBrush(Color.White), cellRect);
			}
			else
			{
				g.FillRectangle(new SolidBrush(Color.Gray), cellRect);
			}

			foreach (CLUBsPiece pi in Pieces)
			{
				pi.Paint(sender, args);
			}
		}

	}
}
